package com.shen.demo.modules.backdoor.controller;

import com.shen.demo.modules.backdoor.service.BackDoorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Objects;

/**
 * 后台控制层接口
 *
 * @author syn
 */
@Slf4j
@RestController
@RequestMapping("/backdoor")
public class BackDoorController {
    @Value("${services.download.file-dir:/opt/njzf/dify-save-data/}")
    private String fileDir;

    @Autowired
    private BackDoorService backDoorService;

    /**
     * 打印文件二进制编码
     *
     * @param filePath 文件路径
     * @return 文件二进制编码
     */
    @PostMapping("/printFileCode")
    public String printFileCode(@RequestParam(name = "filePath") String filePath) {
        return backDoorService.printFileCode(filePath);
    }

    /**
     * 插入文件二进制编码
     *
     * @param filePath 文件路径
     * @return 插入结果
     */
    @Transactional
    @PostMapping("/insertFileCode")
    public String insertFileCode(@RequestParam(name = "filePath") String filePath) {
        return backDoorService.insertFileCode(filePath);
    }

    /**
     * 生成文件下载链接
     *
     * @param fileContent 文件内容
     * @param fileName    文件名称
     * @return 生成文件到服务器本地并生成下载链接
     */
    @PostMapping("/buildFile")
    public String buildFile(@RequestParam(name = "fileContent") String fileContent, @RequestParam(name = "fileName") String fileName) {
        return backDoorService.buildFile(fileContent, fileDir, fileName);
    }

    /**
     * 生成文件下载链接
     *
     * @param fileContentOne   文件内容1
     * @param fileContentTwo   文件内容2
     * @param fileContentThree 文件内容3
     * @param fileName         文件名称
     * @return 生成文件到服务器本地并生成下载链接
     */
    @PostMapping("/multiContentBuildFile")
    public String buildFile(@RequestParam(name = "fileContentOne") String fileContentOne, @RequestParam(name = "fileContentTwo") String fileContentTwo, @RequestParam(name = "fileContentThree") String fileContentThree, @RequestParam(name = "fileName") String fileName) {
        String fileContent = fileContentOne + fileContentTwo + fileContentThree;
        return backDoorService.buildFile(fileContent, fileDir, fileName);
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @return 从浏览器下载文件，从服务器的路径下载到本地
     */
    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> download(@RequestParam(name = "fileName") String fileName) {
        if (Objects.isNull(fileName)) {
            throw new RuntimeException("文件名不能为空");
        }
        try {
            String filePath = fileDir + fileName;
            File file = new File(filePath);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
            return ResponseEntity.ok().headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));
        } catch (UnsupportedEncodingException e) {
            log.error("URL编码异常", e);
        }
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(null);
    }
}
